//
// Simple string utilities
//
// Author: Alex V. Boreskoff <alexboreskoff@mtu-net.ru>, <steps3d@narod.ru>
//

#include	"StringUtils.h"

std::string	trim ( const std::string& str )
{
	int	len = (int)str.length ();
	int	i, j;

	for ( i = 0; i < len && isspace ( str [i] ); i++ )
		;

	for ( j = len - 1; j >= 0 && isspace ( str [j] ); j-- )
		;

	return str.substr ( i, j - i + 1 );
}

std::string	replaceTabs ( const std::string& str )
{
	int	len = (int)str.length ();
	std::string	s   = str;

	for ( int i = 0; i < len; i++ )
		if ( s [i] == '\t' )
			s [i] = ' ';

	return s;
}

void	parseString ( const std::string& str, std::string& cmd, std::string& args )
{
	int	len = (int)str.length ();
	int	pos;

	for ( pos = 0; pos < len && str [pos] != ' ' && str [pos] != '\t'; pos++ )
		;

	cmd  = str.substr ( 0, pos );
	args = replaceTabs ( trim ( str.substr ( pos ) ) );
}

std::string	dequote ( const std::string& str )
{
	if ( str [0] == '\"' || str [0] == '\'' )			// remove quotes
		return str.substr ( 1, str.length () - 2 );

	return str;
}

bool isPathFileNameDelimeter(char c)
{
	return ((c=='\\') || (c == '/'));
}
char *ExtractFileName(const char *filename)
{
	int l = (int)strlen(filename);
	if(l<1)
		return 0;

	int ss=0,es=0;

	for(int i=l;i>0;i--)
	{
		char c = filename[i];
		if(ss==0 && isPathFileNameDelimeter(c))
			ss = i+1;
		if(es==0 && c == '.')
			es = i;
	}

	if(es==0)
		es = l;

	if(es==ss)
		return 0;

	char *r = new char[es-ss+1];
	for(int i=ss;i<es;++i)
	{
		r[i-ss] = filename[i];
	}
	
	r[es-ss]=0;
	return r;
}

char *ExtractFileExt(const char *filename)
{
	int l = (int)strlen(filename);
	if(l<1)
		return 0;

	int es=0;
	for(int i=0;i<l;i++)
	{
		if(filename[i]=='.')
			es = i+1;
	}

	if(es==0)
		return 0;

	char *r = new char[l-es+1];

	for(int i=es;i<l;++i)
	{
		r[i-es] = filename[i];
	}

	r[l-es]=0;
	return r;
}

char *ExtractFilePatch(const char *filename)
{
	int l = (int)strlen(filename);
	if(l<1)
		return 0;

	int ss=-1;
	for(int i=0;i<l;i++)
	{
		if(isPathFileNameDelimeter(filename[i]))
			ss = i;
	}

	if(ss<0)
		return 0;

	char *r = new char[ss+1];

	for(int i=0;i<ss;++i)
	{
		r[i] = filename[i];
	}

	r[ss]=0;

	return r;
}
